# -*- coding: utf-8 -*-
import os,sys,shutil

def compare_and_copy(source_dir,exist_dir,target_dir):
    """
    参数:
        source_dir: 源目录路径
        exsit_dir: 已转化路径
        target_dir: 目标目录路径
    """
    li_exist=[]
    for root, dirs, files in os.walk(exist_dir):
        for file in files:
            if file.endswith('.md'):
                li_exist.append("".join(os.path.basename(file).split('.')[0:-1]))
                
    
    for root, dirs, files in os.walk(source_dir):
        # 1. 处理当前目录的.md文件
        for file in files:
            if file.endswith('.pdf'):
                file_name="".join(os.path.basename(file).split('.')[0:-1])
                if file_name not in li_exist:
                    src_path = os.path.join(root, file)#full path.
                    rel_path = os.path.relpath(root, source_dir)#relate dir.
                    dst_dir = os.path.join(target_dir, rel_path)#dst_dir.
#                   复制文件并保留元数据
                    shutil.copy2(src_path, dst_dir)
                    print(f"已复制: {src_path} -> {os.path.join(dst_dir, file)}")

def do_copy(source_dir,exist_dir,target_dir):
    # 验证目录存在
    if not os.path.isdir(source_dir):
        print(f"错误: 源目录 '{source_dir}' 不存在")
        sys.exit(1)
    if not os.path.isdir(exist_dir):
        print(f"错误: 比较目录 '{exist_dir}' 不存在")
        sys.exit(1)
    # 运行复制操作
    try:
        compare_and_copy(source_dir,exist_dir,target_dir)
        print(f"\n比较复制操作完成!")
    except Exception as e:
        print(f"操作出错: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    pt_i=r"/media/sq/F:/A_Andrewz/B_Study/CSSCI/03_archive"
    pt_e=r"/media/sq/F:/A_Andrewz/B_Study/CSSCI/04_md_ICT"
    pt_o=r"/media/sq/F:/A_Andrewz/B_Study/CSSCI/09_output"
    do_copy(pt_i,pt_e,pt_o)
    
        